package com.lwt.monstermall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lwt.monstermall.cart.feign.ProductFeignService;
import com.lwt.monstermall.cart.interceptor.CartInterceptor;
import com.lwt.monstermall.cart.service.CartService;
import com.lwt.monstermall.cart.to.UserInfoTo;
import com.lwt.monstermall.cart.vo.CartItemVo;
import com.lwt.monstermall.cart.vo.CartVo;
import com.lwt.monstermall.cart.vo.SkuInfoVo;
import com.lwt.monstermall.common.constant.CartConstant;
import com.lwt.monstermall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @program: monstermall
 * @author: 大怪
 * @create: 2022-02-27 15:02
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public CartItemVo addToCart(Long skuId, Integer num){
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            CartItemVo cartItemVo = new CartItemVo();
            //购物车没有此商品
            //2.新商品信息添加到购物车
            //1.远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                R info = productFeignService.info(skuId);
                SkuInfoVo skuinfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuId);
                cartItemVo.setCheck(true);
                cartItemVo.setImage(skuinfo.getSkuDefaultImg());
                cartItemVo.setCount(num);
                cartItemVo.setTitle(skuinfo.getSkuTitle());
                cartItemVo.setPrice(skuinfo.getPrice());
            },executor);

            //2.远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(values);
            }, executor);


            CompletableFuture.allOf(getSkuInfo,getSkuSaleAttrValues).join();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;
        }else {
            CartItemVo cartItemVo = new CartItemVo();
            cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItemVo item = JSON.parseObject(str, CartItemVo.class);
        return item;
    }

    @Override
    public CartVo getCart(){
        CartVo cart = new CartVo();
        //1.登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null){
            //1.登录
            String cartKey =CartConstant.CART_PREFIX+userInfoTo.getUserId();
            //2.如果临时购物车的数据还没有合并，进行合并
            String tempCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null){
                //临时购物车有数据，需要合并
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车
                clearCart(tempCartKey);
            }

            //获取登录后的购物车数据(包括合并的临时购物车)
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            //2.没登录
            String cartKey =CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            //获取临时购物车的所有项
            List<CartItemVo> cartItem = getCartItems(cartKey);
            cart.setItems(cartItem);
        }

        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }else {
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            //获取所有被选中的购物项
            return cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item->{
                        //更新为最新价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());
        }
    }


    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if(userInfoTo.getUserId() != null){
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hash = redisTemplate.boundHashOps(cartKey);
        return hash;
    }

    private List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size()>0){
            List<CartItemVo> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItemVo itemVo = JSON.parseObject(str, CartItemVo.class);
                return itemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

}
